<template>
  <div class="app-container page-wood-sales-note">
       
    <el-row :gutter="10" class="sumbit-btn-group mb8">
      <template v-if="!returnId">
       <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="saveHandleAdd"
          v-hasPermi="['business:salesReturn:add']"
          >保存并新增</el-button
        >
      </el-col>
      <template v-if="form.orderStatus != 3">
        <el-col :span="1.5">
            <el-button
            type="success"
            plain
            icon="el-icon-edit"
            size="mini"
            @click="submitForm"
            v-hasPermi="['business:salesReturn:add']"
            >保存</el-button
            >
        </el-col>
      </template>
      </template>
      <template v-else>
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="newAddSell"
            v-hasPermi="['business:salesReturn:add']"
            >新增</el-button
          >
        </el-col>
        <template v-if="form.orderStatus != 3">
          <el-col :span="1.5">
          <el-button
            type="success"
            icon="el-icon-edit"
            size="mini"
            @click="setAuditStatus"
            v-hasPermi="['business:salesReturn:edit']"
            >{{ form.auditStatus == 0 ? "审核" : "反审核" }}</el-button
          >
        </el-col>
        </template>
        <template v-if="form.auditStatus != 1">
          <el-col :span="1.5">
            <el-button
              type="success"
              plain
              icon="el-icon-edit"
              size="mini"
              @click="setAuditStatus(2)"
              v-hasPermi="['business:salesReturn:edit']"
              >保存</el-button
            >
          </el-col>
        </template>
      </template>
    </el-row>

    <div class="table-area">
      <el-form
        :model="form"
        ref="form"
        :inline="true"
        v-show="showSearch"
        :rules="rules"
        label-width="90px"
      >
     
          <el-form-item label="单据日期"  prop="billTime">
          <el-date-picker
            clearable
            size="small"
            v-model="form.billTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择单据日期"
            :disabled="disabled"
          >
          </el-date-picker>
        </el-form-item>
 
          <el-form-item label="单据编号" prop="returnId">
            <el-input
            v-model="form.returnId"
            placeholder="请输入单据编号"
            :disabled="true"
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>

        <el-form-item label="出库单号" prop="deliveryId">
            <el-input
            v-model="form.deliveryId"
            placeholder="请输入出库单号"
            :disabled="true"
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>

  
       <JustTimeInventory
          @selectItemsClick="selectItemsClick"
          :salesType = 'salesType'/>
      <!-- 表格开始 -->
      <TableForm
          ref="TableForm"
          :list="form.woodSalesReturnGoodsList"
          :column="getSalesTableData"
          :summary="true"
          :loading="loading"
          :disabled="disabled"
      >
      </TableForm>
      <!-- 表格结束 -->
      
      <!-- 备注信息 -->
      <el-form-item class="form-remark" prop="remark">
          <el-input
            type="textarea"
            placeholder="请输入备注信息"
            v-model="form.remark"
            clearable
            size="small"
            rows="5"
          />
        </el-form-item>
        <img
          v-if="form.auditStatus == 1 && form.orderStatus != 3"
          :src="img.audit"
          class="img-audit"
        />
         <img v-if="form.orderStatus == 3" :src="img.close" class="img-audit" />
      </el-form>
    </div>
  </div>
</template>

<script>

import JustTimeInventory from "@/components/JustTimeInventory";
import TableForm from "@/components/TableForm/preset";

export default {
  name: "salesDelivery",
  components: {
    JustTimeInventory,
    TableForm
    },
  data() {
    return {
      // 遮罩层
      loading: false,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 商品实时库存查询参数
      queryParams: {
        pageSize:10,
        pageNum:1,
        baleNum: null,
      },
      // 表单参数
      formData:{},
      form: {
        returnId:"",
        isStatus: "0",
        auditStatus: 0,
        deliveryId: "",
        // 销售订单信息表格数据
        woodSalesReturnGoodsList: [
          {
            baleNum: "", // 包号
            goodsName: "", // 品名
            brandName: "", // 品牌
            level:"", //等级
            warehouse: "", // 仓库
            ply: 0, // 厚度
            width: 0, // 宽度
            length: 0, // 长度
            sliceCount: 0, // 片数
            pieceCount: 0, // 件数
            inCount: 0, // 方数
            includedTaxPrice: 0, //含税单价
            price: 0, // 单价
            money: 0, // 金额
            goodsStatus: "", // 货物状态
            pactName: "", //开证公司
            remark: "", // 备注
            gcountId: ""
          },
        ],
      },
      // 表格数据
      getSalesTableData :[
          { label: "包号", changeBlur: this.searchBaleNum},
          { label: "品名"},
          { label: "品牌"},
          { label: "等级"},
          { label: "仓库"},
          {
            label: "厚度(mm)",
            inputType: "none",
            summary: true
          },
          {
            label: "宽度(mm)",
            inputType: "none",
            summary: true
          },
          {
            label: "长度(m)",
            inputType: "none",
            summary: true
          },
          { label: "片数"},
          { label: "件数",  afterChange: this.moneyCount},
          { label: "单包方数", afterChange: this.moneyCount},
          { label: "方数", inputType: "none", value:'count', sync:'inCount'},
          {
            label: "含税单价", 
            value: 'includedTaxPrice',
            sync: 'price',
            onchange: this.moneyCount,
            },
          { label: "金额"},
          { label: "货物状态", inputType: "none", summary: true,},
          { label: "开证公司", inputType: "none",value:'pactName'},
          { 
            label: "源单序号",
            value: "pactName",
            inputType: "none",
            summary: true,
        },
          {label: "备注(批量)"},
      ],
      // 表单校验
      rules: {
          billTime: [
            { required: true, message: '单据日期不能为空', trigger: "blur"},
          ],
          returnId: [
            { required: true, message: '单据编号不能为空', trigger: "blur"},
          ],
          deliveryId: [
            { required: true, message: '出库单号不能为空', trigger: "blur"},
          ],
    
      },

      //订单号 
      returnId: "",
      mouseShow:false,
      //组件控制显示传值 
      salesType: 'salesOrder',
    
      img: {
        audit: require("@/assets/images/bg@audit.png"),
        close: require("@/assets/images/bg@closed.png"),
      },
    };
  },
  created() {
    let { id } = this.$route.params;
    this.returnId = id;
    id && this.getSalesDetail()
    
    this.getReceiptCode();

  },
  computed: {
      disabled() {
        if( this.form.auditStatus == 1) {
           return  !!this.orderId
        }
      },
    
  },
  methods: {
    // 获取单据编号
    getReceiptCode(){
      let { id } = this.$route.params;
      if(id){
         this.form.deliveryId = id;
        return false;
      }
      this.$Api.onlyId.getId().then(( res) =>{
        let { data} = res;
        this.form.returnId = data;
    })
    },
    // 包 数据选择
    selectItemsClick(newData){
        let newSalesDeliveryGoodsList = [];
        let { woodSalesDeliveryGoodsList, deliveryId ,customerId,customerName,salesCode,salesName } = newData;
        woodSalesDeliveryGoodsList.map( (v) =>{
           
            let item = { customerName: customerName ,customerId :customerId,salesName : salesName,salesCode : salesCode};
            newSalesDeliveryGoodsList.push(Object.assign({}, v, item));
            
        })
        this.form.woodSalesReturnGoodsList = newSalesDeliveryGoodsList;
        this.form.deliveryId = deliveryId;
        this.form.customerName = customerName;
        this.form.salesName = salesName;
        
    },
    // 金额计算 ： 单价 * 方数  
    moneyCount(d) {
      let { count, includedTaxPrice } = d;
      let t = ((Number(includedTaxPrice) || 0) * ( Number(count) || 0)).toFixed(3);
      this.price = includedTaxPrice;
      d.money = t;
      },

    // 获取详情
    getSalesDetail() {
      let { returnId } = this;
        this.$Api.sales.return.detail(returnId).then((res) => {
        let { data, code } = res;
        if (code === 200) {
          data.woodSalesReturnGoodsList = data.woodSalesReturnGoodsList
          this.form = data;
        }
      });
    },

    // 取消按钮
    cancel() {
      this.$refs["form"].validate(valid =>{
        if(valid){
          this.dialogTable = false;
          this.open = false; 
        }
      }) 
      
    },
    // 表格重置
    reset() {
       this.form.woodSalesReturnGoodsList=[
        {
           baleNum: null, // 包号
            goodsName: null, // 品名
            brandName: null, // 品牌
            level:null, //等级
            warehouse: null, // 仓库
            ply:null, // 厚度
            width:null, // 宽度
            length:null, // 长度
            sliceCount:null, // 片数
            pieceCount:null, // 件数
            inCount:null, // 方数
            includedTaxPrice: null, // 单价
            money: null, // 金额
            goodsStatus: null, // 货物状态
            pactName: null, //开证公司
            remark: null, // 备注
        },
      ]
    },
 
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 保存提交按钮 */
    submitForm() {
      let {woodSalesReturnGoodsList} = this.form;

      woodSalesReturnGoodsList.forEach( (item) =>{
          item.gcountId;
          // item.count = item.inCount
        })
 
        this.$refs["form"].validate( (pass,error) =>{
        pass &&
        this.$refs["TableForm"].checkForm(
          ( TableFormPass, error) =>{
            if (TableFormPass) {
              this.$Api.sales.return.add(this.form).then((res) => {
              if( res.code == 200) {
                this.returnId = res.data;
                this.msgSuccess("操作成功");
                const id = this.returnId;
                    let path = `/sales/salesReturn/list/${id}`;
                    this.$router.push({
                      path,
                    });  
              }else {
                this.$message.error('操作失败');
              }
            });
            }
          }
        )
      })
    },
        //保存并新增 
    saveHandleAdd() {
      this.submitForm();
      this.reset();
      this.form.returnId = null
    

    },
    // 新增
    newAddSell () {
      this.$router.push({ path: '/sale/receipts/sales-return' });
      this.reset();
    },
    // 审核与反审核 审核状态;0未审核 1已审核
    setAuditStatus(state){
      let { returnId } = this;
      let { auditStatus} = this.form;
      let setStatus = auditStatus == 0 ? '审核' : '反审核'
      this.$confirm('是否确认'+`${ state == 2 ? "保存" : setStatus }`+'采购订单信息编号为"' + returnId + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
              let postData =  JSON.parse(JSON.stringify(this.form));
              if( state == 2) {
                  auditStatus = 1
              }else {
                   let nextAudit = auditStatus == 1 ? 0 : 1;
                   postData.auditStatus = nextAudit;
              }
              this.$Api.sales.return.edit(postData).then((res) => {
              if( res.code == 200) {
                this.getSalesDetail()
                state == 2 ?  this.msgSuccess("保存成功") : this.msgSuccess("审核成功");
              }else {
                this.$message.error('操作失败');
    
              }
            }).catch(() => {});
        }).catch(() => {});
        
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm(
        '是否确认删除销售订单信息编号为"' + ids + '"的数据项?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(function () {
          return delWoodPurchaseIn(ids);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm("是否确认导出所有销售订单信息数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.exportLoading = true;
          return exportWoodPurchaseIn(queryParams);
        })
        .then((response) => {
          this.download(response.msg);
          this.exportLoading = false;
        })
        .catch(() => {});
    },
  },
};
</script>

<style lang="scss" scoped>
::v-deep.page-wood-sales-note {
  .img-audit{
      position: absolute;
      right: 30px;
      bottom: 30px;
      transform: rotate(-18deg);
      pointer-events: none;
  }
  .add-wood-just-time{
    margin:0 0 15px 15px;
    .el-button--primary.is-plain{
    padding: 0;
  }
  }
  
  .sumbit-btn-group {
    margin: 0 0 20px 0;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    
  }
  .btn-group {
    display: flex;
    align-items: center;
    justify-content: space-evenly;
  }

  .disabled {
    color: #a8a8a8;
  }

  .error {
    color: #fa3e3e;
  }

  .form-remark {
      display: grid;
      margin: 20px 15px 15px;
       .el-form-item__contentt {
        display: inline-block ;
        width: 100% ;
    }
  }
 
}
</style>
